package com.OA.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.OA.entity.Message;
import com.OA.entity.User;
import com.OA.service.ZZH_EmailService;
import com.OA.util.Page;
import com.alibaba.fastjson.JSON;

/**
 * 站内信控制层
 * @author Administrator
 *
 */
@Controller
@RequestMapping("email")
public class ZZH_EmailController {
	
	@Autowired
	private ZZH_EmailService emailService;
	/**
	 * 用于测试登录
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="userLogin.do")
	public void loginUser(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String userName=req.getParameter("userName");
		if(userName !=""){
			Message message=emailService.login(userName);
			req.getSession().setAttribute("user", message);
			resp.getWriter().write(JSON.toJSONString(message));
			resp.getWriter().flush();
			resp.getWriter().close();
		}
	}
	/**
	 * 获取写信页面下拉框用户
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="optionUser.do")
	public void optionUser(HttpServletRequest req, HttpServletResponse resp) throws IOException{
//		System.out.println("正在访问站内信--------写信");
		resp.setCharacterEncoding("utf-8");
		List<User> list = emailService.optionByuserName();
		//获取session中数据
		User userId =(User) req.getSession().getAttribute("user");
		//创建list集合
		List<User> user = new ArrayList<User>();
		//循环数据库中数据判断，收件人下拉框是否存在自己，不是则添加到list集合中
		for (User us : list) {
			if(us.getUserId() != userId.getUserId()){
				user.add(us);
			}
		}
		resp.getWriter().write(JSON.toJSONString(user));
		resp.getWriter().flush();
		resp.getWriter().close();
	}
	/**
	 * 添加到草稿箱/发送邮件
	 * @param message
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="draftAndOutBox.do")
	public void draftAndOutBox(Message message,String draft,Integer mid,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(mid != null){
			emailService.deleteById(mid);
		}
		List<Message> login = emailService.loginById(message.getRecipients());
		if(login.size()>0){
			Message mess = new Message( message.getTitle(), message.getContent(), message.getAddresser(),
					message.getAddresserId(), message.getRecipients(), login.get(0).getUserId(), 0,Integer.valueOf(draft), 0);
			emailService.draftAndOutBox(mess);
			resp.getWriter().write("success");
		}else{
			resp.getWriter().write("error");
		}
		resp.getWriter().flush();
		resp.getWriter().close();
	}
	/**
	 * 查询所有草稿箱及按条件查询草稿箱/查询所有发件箱及按条件查询发件箱
	 * @param map
	 * @return
	 */
	@RequestMapping(value="LoadDraftAndOutBox.do")
	public void LoadDraftAndOutBox(int pageNo,int pageSize,int draft,HttpServletResponse resp,Integer addresserId,String keyword,String direction) throws IOException{
//		if(draft == 1){
//			System.out.println("正在访问站内信--------草稿箱");
//		}else if(draft == 0){
//			System.out.println("正在访问站内信--------发件箱");
//		}
		resp.setCharacterEncoding("utf-8");
		Map<String,Object> map = new HashMap<String,Object>();
		if(keyword != null && !keyword.equals("")){
			map.put("keyword","%"+keyword+"%");
		}else{
			map.put("keyword",keyword);
		}
		if(direction != null && !direction.equals("")){
			map.put("direction", "%"+direction+"%");
		}else{
			map.put("direction", direction);
		}
		map.put("addresserId", addresserId);
		map.put("draft", draft);
		map.put("beginIndex", (pageNo-1)*pageSize);
		map.put("pageNo", pageNo);
		map.put("pageSize", pageSize);
		Page<Message> page = emailService.loadDraftAndOutBox(map);
		//date类型的值转换为string类型的值
		SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		for(int i=0;i<page.getRows().size();i++){
			String str = data.format(page.getRows().get(i).getMessageDate());
			page.getRows().get(i).setStringDate(str);
		}
		resp.getWriter().write(JSON.toJSONString(page));
		resp.getWriter().flush();
		resp.getWriter().close();
	}
	/**
	 * 删除数据
	 * @param message
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="deleteById.do")
	public void deleteById(@RequestParam(value="mid[]")Integer[] mid,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		for(int i = 0;i<mid.length;i++){
			emailService.deleteById(mid[i]);
		}
	}
	/**
	 * 恢复数据
	 * @param mid
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="recoverData.do")
	public void recoverData(@RequestParam(value="mid[]")Integer[] mid,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		for(int i = 0;i<mid.length;i++){
			emailService.recoverById(mid[i]);
		}
	}
	/**
	 * 查询所有收件箱及条件查询收件箱
	 * @param pageNo
	 * @param pageSize
	 * @param recipientsId
	 * @param keyword
	 * @param direction
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="LoadInBox.do")
	public void LoadInBox(int pageNo,int pageSize,Integer recipientsId,String keyword,String direction,HttpServletRequest req,HttpServletResponse resp) throws IOException{
//		System.out.println("正在访问站内信--------收件箱");
		resp.setCharacterEncoding("utf-8");
		Map<String,Object> map = new HashMap<String,Object>();
		if(keyword != null && !keyword.equals("")){
			map.put("keyword","%"+keyword+"%");
		}else{
			map.put("keyword",keyword);
		}
		if(direction != null && !direction.equals("")){
			map.put("direction", "%"+direction+"%");
		}else{
			map.put("direction", direction);
		}
		map.put("recipientsId", recipientsId);
		map.put("beginIndex", (pageNo-1)*pageSize);
		map.put("pageNo", pageNo);
		map.put("pageSize", pageSize);
		Page<Message> page = emailService.loadInBox(map);
		//date类型的值转换为string类型的值
		SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		for(int i=0;i<page.getRows().size();i++){
			String str = data.format(page.getRows().get(i).getMessageDate());
			page.getRows().get(i).setStringDate(str);
		}
		resp.getWriter().write(JSON.toJSONString(page));
		resp.getWriter().flush();
		resp.getWriter().close();
	}
	/**
	 * 添加到回收站
	 * @param message
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="addRecycleStand.do")
	public void addRecycleStand(@RequestParam(value="mid[]")Integer[] mid,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		for(int i = 0;i<mid.length;i++){
			emailService.insertRecycleStand(mid[i]);
		}
	}
	/**
	 * 回收站加载发件箱
	 * @param pageNo
	 * @param pageSize
	 * @param resp
	 * @param userId
	 * @throws IOException
	 */
	@RequestMapping(value="loadRecycleOutBox.do")
	public void loadRecycleOutBox(int pageNo,int pageSize,HttpServletResponse resp,Integer userId) throws IOException{
//		System.out.println("正在访问站内信--------回收站");
		resp.setCharacterEncoding("utf-8");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("pageNo", pageNo);
		map.put("pageSize", pageSize);
		map.put("userId", userId);
		map.put("beginIndex", (pageNo-1)*pageSize);
		Page<Message> page = emailService.selectRecycleOutBox(map);
		//date类型的值转换为string类型的值
		SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		for(int i=0;i<page.getRows().size();i++){
			String str = data.format(page.getRows().get(i).getMessageDate());
			page.getRows().get(i).setStringDate(str);
		}
		resp.getWriter().write(JSON.toJSONString(page));
		resp.getWriter().flush();
		resp.getWriter().close();
	}
	/**
	 * 回收站加载发件箱
	 * @param pageNo
	 * @param pageSize
	 * @param resp
	 * @param userId
	 * @throws IOException
	 */
	@RequestMapping(value="loadRecycleInBox.do")
	public void loadRecycleInBox(int pageNo,int pageSize,HttpServletResponse resp,Integer userId) throws IOException{
		resp.setCharacterEncoding("utf-8");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("pageNo", pageNo);
		map.put("pageSize", pageSize);
		map.put("userId", userId);
		map.put("beginIndex", (pageNo-1)*pageSize);
		Page<Message> page = emailService.selectRecycleInBox(map);
		//date类型的值转换为string类型的值
		SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		for(int i=0;i<page.getRows().size();i++){
			String str = data.format(page.getRows().get(i).getMessageDate());
			page.getRows().get(i).setStringDate(str);
		}
		resp.getWriter().write(JSON.toJSONString(page));
		resp.getWriter().flush();
		resp.getWriter().close();
	}
	/**
	 * 根据id查询收件箱数据进行表单回填
	 * @param mid
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="inBoxById.do")
	public void inBoxById(Integer mid,Integer state,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		resp.setCharacterEncoding("utf-8");
		//把未读状态改为已读状态
		if(state == 0){
			emailService.inBoxByIdState(mid);
		}
		Message message = emailService.inBoxById(mid);
		resp.getWriter().write(JSON.toJSONString(message));
		resp.getWriter().flush();
		resp.getWriter().close();
	}
}
